#include "DB_Manager.h"






DB_Manager::DB_Manager()
{
	    QStringList drivers = QSqlDatabase::drivers();
	    // remove compat names
	    drivers.removeAll("QMYSQL3");
	    drivers.removeAll("QOCI8");
	    drivers.removeAll("QODBC3");
	    drivers.removeAll("QPSQL7");
	    drivers.removeAll("QTDS7");
      hottables << "APPCASE" << "WEB_ICONE_ATTRIBUTI" << "APP_PICS" << "LUOGHI" << "APP_CALTIMELINE" << "APPLICATION_SETTING"; 
}


bool DB_Manager::Connect( const QString sheme , int trac )
{
    Actual_Scheme = sheme;
	  std::cout <<  "new connection SetDb->" << qPrintable(sheme) << "<- Nr." << trac << "    \n" << std::endl; 
    ////////#define SAMPLEMYSQLSCHEME \
    ////////QString( "mysql://username:pass@host:port/database" )
    QUrl dns(sheme,QUrl::TolerantMode);
    const QString dbase = dns.path().replace("/","");
    QStringList drivers = QSqlDatabase::drivers();
    type = "Q"+dns.scheme().toUpper();
	  /////////std::cout << "######### type   " << qPrintable(type ) << "\n" << std::endl;
    if (!drivers.contains(type)) {
    std::cout << "######### " << qPrintable(tr("Unable to Load Driver %1").arg(type)) << "\n" << std::endl;
    return false;      
    }
    ConnectionName = QString("master_mysql_%1").arg(trac);
		db = QSqlDatabase::addDatabase(type,ConnectionName);
    if (type == "QMYSQL") {
    //////////db.setConnectOptions("CLIENT_INTERACTIVE=0");   
    }
    db.setDatabaseName(dbase);
    if (dns.host().size() > 0) {
    db.setHostName(dns.host());
    }
    if (dns.userName().size() > 0) {
    db.setUserName(dns.userName());
    }
    if (dns.password().size() > 0) {
    db.setPassword(dns.password());
    }
    if (dns.port() > 0) {
    db.setPort(dns.port());
    }
    if (!db.open()) {
    std::cout << "######### Unable to connect on [" << qPrintable(dbase) << "]" << std::endl;
    return false;
    } else {
    	
    	    infodb = "("+dbase + ") ";
    	    QSqlQueryModel *model = new QSqlQueryModel();
            model->setQuery("SHOW GLOBAL VARIABLES",db);
            
    	for (int e = 0; e < model->rowCount(); ++e)   {
         QSqlRecord r = model->record(e);
         const QString var = r.value(0).toString();
         if (var == "version" || var == "version_comment" || var == "version_compile_machine" || var=="version_compile_os") {
         	infodb.append(r.value(1).toString() +" / ");
         }
                  
         }
         infodb.append(" Host:"+dns.host());
         
    	
    	
    Load();  /* load cache results !!!!! */
		return true;
		}
	
}

/* cahce icon and translation */
void DB_Manager::Load()
{
    const QString newversionsql = "ALTER TABLE `TIPO_OGGETTI` ADD `TIPO_TI` INT( 1 ) DEFAULT '0' NOT NULL AFTER `AUTOR`;";
    const QString newversionsql_2 = "ALTER TABLE `TIPO_OGGETTI` ADD `POS` INT( 2 ) DEFAULT '1' NOT NULL AFTER `TIPO_TI`;";
    const QString newversionsql_3 = "ALTER TABLE `APPCASE` ADD `REG` INT( 2 ) DEFAULT '0' NOT NULL AFTER `UP_200`";
     
    
    
    QStringList campi = FieldList("TIPO_OGGETTI");
    if (!campi.contains("TIPO_TI")) {
        if (UpDateQuery(newversionsql)) {
        QMessageBox::information(0, tr("SQL message"),tr("Update successful new field TIPO_TI"));
        } else {
        QMessageBox::information(0, tr("SQL message"),tr("Unable to append field TIPO_TI!"));  
        }
    }
    QStringList campi2 = FieldList("TIPO_OGGETTI");
    if (!campi2.contains("POS")) {
        if (UpDateQuery(newversionsql_2)) {
        QMessageBox::information(0, tr("SQL message"),tr("Update successful new field TIPO_TI"));
        } else {
        QMessageBox::information(0, tr("SQL message"),tr("Unable to append field TIPO_TI!"));  
        }
    }
    QStringList campi3 = FieldList("APPCASE");
     if (!campi3.contains("REG")) {
        if (UpDateQuery(newversionsql_3)) {
        QMessageBox::information(0, tr("SQL message"),tr("Update successful new field Regione"));
        } else {
        QMessageBox::information(0, tr("SQL message"),tr("Unable to append field Regione!"));  
        }
    }
    
    
    
    StreamIcone = Get_Setting(_NR_ICONE_ATTRIBUTI_);
    trdoc = retranslate_now();
}

bool DB_Manager::UpDateQuery( const QString ese )
{
    return UpDateQuery(ese,current());
}

bool DB_Manager::UpDateQuery( const QString ese , QSqlDatabase dbcurrent )
{
    bool funo;
    QSqlQuery query("",dbcurrent);
        funo = query.exec(ese);
        if ( funo ) {
         return true;
        }
  QMessageBox::warning(0, tr("Error SQL!"),tr("Unable to play query %1!").arg(query.lastError().text()));
  return false;    
}



QStringList DB_Manager::FieldList( const QString table ) 
{
    if (!db.open())  {
    return QStringList();
    }
    const QString InfoTablesql = QString("SHOW COLUMNS FROM %1").arg(table);
    QSqlQueryModel *Amodel = new QSqlQueryModel();
    Amodel->setQuery(InfoTablesql,db);
    QStringList cols;
    cols.clear();
    for (int i = 0; i < Amodel->rowCount(); ++i) {
        const int pane = i;
        cols.append(Amodel->data(Amodel->index(i,0)).toString());
    }
    return cols;
} 


void DB_Manager::ExportAllTable()
{
    QDate nowtaga = QDate::currentDate();
    bool ok;
    QString ba = nowtaga.toString("d.M.yyyy")+"_full.sql";
    
    QString cfileName = QFileDialog::getSaveFileName(0, "Export MYSQL table format",ba, "*.sql");
    if (cfileName.size() > 0 && cfileName !=ba ) {
                 if (!cfileName.endsWith(".sql")) {
                     cfileName = cfileName+".sql"; 
                 }
    } else {
    return;
    }
    QString stream;
    QStringList alltable = db.tables(QSql::AllTables);
		
		if (alltable.size() < 1) {
		QMessageBox::warning(0, tr("Error SQL!"),tr("No table found!"));
		return;
		}
		
    for (int i = 0; i < alltable.size(); ++i)  {
        const QString onetab = alltable.at(i);
        stream.append("\n");
        stream.append(TableMysqlStruct(onetab,db,true));
        stream.append("\n");
        stream.append(StreamTableDump(onetab,db));
        stream.append("\n");
    }
    
        QFile f( cfileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw << stream;
        f.close();
        } else {
            QMessageBox::warning(0, tr("Error SQL File!"),tr("Unable to write on this file ..."));
        }
    
    
    
    
}



QIcon DB_Manager::createColorToolButtonIcon( QColor e  )
    {
    QPixmap pixmap(50, 50);
    pixmap.fill(e);
    QPainter painter(&pixmap);
    return QIcon(pixmap);       /////  createColorToolButtonIcon( QColor(Qt::red)  )
       ///////////////  createColorToolButtonIcon( QColor(Qt::green)  )
}

void DB_Manager::FillCombo(  QComboBox  *  box )
{
	  box->clear();
	  QStringList alltable = db.tables(QSql::AllTables);
		if (alltable.size() < 1) {
		QMessageBox::warning(0, tr("Error SQL!"),tr("No table found!"));
		return;
		}
    
     
     
    
    
		for (int i = 0; i < alltable.size(); ++i)  {
        const QString onetab = alltable.at(i);
        if (hottables.contains(onetab)) {
            box->addItem(createColorToolButtonIcon( QColor(Qt::red)  ),onetab , 0 );
        } else {
            box->addItem(createColorToolButtonIcon( QColor(Qt::green)  ), onetab , 1 );
        }
			  
        
        
		}
           box->setCurrentIndex (-1) ;
}


void DB_Manager::FillComboFixQuery(  QComboBox  *  box )
{
	  box->clear();
	  QStringList alltable = db.tables(QSql::AllTables);
		if (alltable.size() < 1) {
		QMessageBox::warning(0, tr("Error SQL!"),tr("No table found!"));
		return;
		}
    box->addItem("SHOW PRIVILEGES",QString("SHOW PRIVILEGES;"));
    ////////QString pas =  QString("SHOW GRANTS FOR %1@localhost").arg(db.databaseName()));
    box->addItem("SHOW GLOBAL VARIABLES",QString("SHOW GLOBAL VARIABLES"));
    ////////////box->addItem("SHOW GRANTS ",pas);
    box->addItem("SHOW TABLE STATUS",QString("SHOW TABLE STATUS FROM %1;").arg(db.databaseName()));
    
    
    box->addItem("SHOW COLLATION LIKE latin ","SHOW COLLATION LIKE 'latin1%';");
    box->addItem("SHOW COLLATION LIKE utf ","SHOW COLLATION LIKE 'utf%';");
		for (int i = 0; i < alltable.size(); ++i)  {
        const QString onetab = alltable.at(i);
			  box->addItem(onetab  +" PROCEDURE ANALYSE()",QString("SELECT * FROM %1 PROCEDURE ANALYSE() ").arg(onetab));
        box->addItem(onetab  +" SHOW CREATE TABLE",QString("SHOW CREATE TABLE %1").arg(onetab));
        box->addItem(onetab  +" SHOW COLUMNS TABLE",QString("SHOW COLUMNS FROM %1").arg(onetab));
		}
    
    
    
    
}


bool DB_Manager::Save_Calendar( const int stnr , const QString stream , const QString web )
{
    QSqlQuery query("",db);
         QString sqlpaint =  QString("REPLACE INTO `APP_CALTIMELINE` VALUES (%1,'%2','%3');")
        .arg(stnr)
        .arg(stream)
        .arg(web);
    return query.exec(sqlpaint);
}


QString DB_Manager::Get_Calendar( const int stnr )
{
    QSqlQuery query("",db);
              query.exec(QString("SELECT NAME FROM APP_CALTIMELINE WHERE ID=%1 LIMIT 1").arg(stnr));
    
    QSqlRecord rec = query.record();
    if (rec.count() !=1) {
      return QString();  
    }
    
     while (query.next()) { 
     return query.value(0).toString();
     }
     return QString();
}




bool DB_Manager::Save_Setting( const int stnr , const QString stream , const QString t )
{
    QSqlQuery query("",db);
         QString sqlpaint =  QString("REPLACE INTO "+t+" VALUES (%1,'%2');")
        .arg(stnr)
        .arg(stream);
    return query.exec(sqlpaint);
}

QString DB_Manager::Get_Setting( const int stnr , const QString t )
{
    QSqlQuery query("",db);
              query.exec(QString("SELECT NAME FROM "+t+" WHERE ID=%1 LIMIT 1").arg(stnr));
    
    QSqlRecord rec = query.record();
    if (rec.count() !=1) {
      return QString();  
    }
    
     while (query.next()) { 
     return query.value(0).toString();
     }
     return QString();
}

QString DB_Manager::TableMysqlStruct( const QString table , QSqlDatabase db , bool dropbefore , bool space ) 
{
    QString comand = "";

    if (table.size() < 1) {

    return comand;

   }
    const QString takia = QString("`%1`").arg(table.toLower());
    const QString takiunix = QString("`%1`").arg(table.toUpper());
    QString dropta = QString("DROP TABLE IF EXISTS `%1`;\n").arg(table.toUpper());
    /////QString fieldvalue = QString("SHOW COLUMNS FROM %1").arg(table);
    QString shemasql = QString("SHOW CREATE TABLE %1").arg(table.toUpper());
    /////int rowi = -1;
     QSqlQuery query(shemasql,db);
       QSqlRecord rec = query.record();
       int sumcol = rec.count();
            while (query.next()) { 
                /////rowi++;
                comand = query.value(1).toString();
                    Q_ASSERT(comand.size() > 1);
                    if (!space) {
                    comand = comand.replace("\n"," ");
                    comand = comand.replace(takia,takiunix);
                    }
                    comand.append(";\n");
                //////qDebug() << "### comand  " << comand;
            }
        if (dropbefore) {
        comand.prepend(dropta);
        }
            
return comand;
}


QString DB_Manager::StreamTableDump( const QString table , QSqlDatabase dbcurrent , int  forcecodecmib )
{
        QTextCodec *codec;
         if (forcecodecmib != 106 ||  forcecodecmib != 0 ) {
         codec = QTextCodec::codecForMib(forcecodecmib);
         }
         QTextDecoder *decoder = codec->makeDecoder();
         
        QStringList Default_Value = DefaultFieldFrom(table,dbcurrent) ; 
        
     QProgressDialog *dlg = new QProgressDialog(0,Qt::Popup);
            dlg->setLabelText (tr("Export table \"%1\" from %2").arg( table.toUpper() ).arg(dbcurrent.hostName()));
            dlg->setCancelButton(0);
            //////dlg->setMaximum(100);
            //////dlg->setValue(0);
    QDate nowtag = QDate::currentDate();
    QSqlQuery query(QString("SELECT * FROM %1").arg(table),dbcurrent);
    QSqlRecord rec = query.record();
    QStringList cvslines;
    QStringList Fname;
    QStringList Fvalue;
    cvslines.clear();
    cvslines.append(QString("\n###### table %1\n\n").arg(table.toUpper()));
    cvslines.append(QString("\n###### date %1\n\n").arg(nowtag.toString("d.M.yyyy")));
    
    
            bool suppoaffect;
            int sumcol = rec.count();
            int sumrow = query.numRowsAffected();
            int recnum = 0;  /* QProgressDialog *dlg; */
            int pasero = 0;
            
            
             while (query.next()) { 
                    recnum++;  /* count fake lines */
                    
                     dlg->setMaximum(100);
                     dlg->setValue((recnum * 100) / sumrow );
                   
                    Fvalue.clear();
                    Fname.clear();
                   
                             for(int i=0;i<sumcol;i++){
                             bool oknr = false;
                             QSqlField fld = rec.field(i);
                             QString value ="";
                             if (forcecodecmib == 106) {
                             QByteArray input = query.value(i).toByteArray();
                             value = G_Quote(QString::fromUtf8(input.data()));
                             } else if (forcecodecmib !=0) {
                                const QByteArray convert = query.value(i).toByteArray();
                              value = G_Quote(decoder->toUnicode(convert ));
                             } else {
                             	value = G_Quote(query.value(i).toString());
                             }
                                     value = value.replace("\n","\\n");
                                     value = value.replace("\t","\\t");
                                     value = value.replace("\r","\\r");
                             const QString typeoffield = QString(QVariant::typeToName(fld.type()));
                                 if ( typeoffield == "int" ) {
                                    int vnummer = value.toInt(&oknr);
                                 }
                             QString fname = rec.fieldName(i);
                                 if (oknr) {
                                 Fvalue.append(value);
                                 } else if (value.isEmpty()) {
                                 Fvalue.append(Default_Value.at(i));     /* grep default */
                                 } else {
                                 Fvalue.append(QString("'%1'").arg(value));  
                                 }
                             }
                             
                    QString Dvalue = Fvalue.join(",");
                    cvslines.append(QString("REPLACE INTO %1 VALUES (%2);\n").arg(table).arg(Dvalue));
                    }
                    dlg->close();
      
           cvslines.append(QString("\n"));
       return cvslines.join("");
}







QStringList DB_Manager::DefaultFieldFrom( const QString table , QSqlDatabase dbcurrent ) 
{
    const QString xdefault = "NULL";
    QStringList defi;
    defi.clear();
    QSqlQuery query(QString("SHOW COLUMNS FROM %1").arg(table.toUpper()),dbcurrent);
    QSqlRecord rec = query.record();
    int sumcol = rec.count();
           while (query.next()) { 
              
                      QString svl = query.value(4).toString(); 
                      if (svl.size() < 1) {
                        defi.append(xdefault);
                      } else {
                        defi.append("'"+svl+"'");
                      }
                    
                  
                         
            }
            
return  defi;
}



bool DB_Manager::UpdatesOggetti( const int titurism , int localid , QMap<QString,QString> fupdates , const int tipo )
{
    if ( fupdates.size() < 1) {
    return false;
    }
	   fupdates.insert("CID_4",QString("%1").arg(titurism));
       fupdates.insert("TIPO_1",QString("%1").arg(IdTipo(tipo)));
       fupdates.insert("TID",QString("%1").arg(tipo));
    
     QStringList Setts;
                Setts.clear();
    QMapIterator <QString,QString> d(fupdates);
                while (d.hasNext()) {
                       d.next();
                       Setts.append(QString("%1='%2'").arg(d.key()).arg(G_Quote(d.value())));
                }
                
                QString upsdax = "UPDATE APPCASE SET ";
                        upsdax.append(Setts.join(","));
                        upsdax.append(QString(" WHERE ID =%1 LIMIT 1").arg(localid));
     QString utrac = QString(" update ID =%1 ").arg(localid);
     qDebug() << "### sqls " << utrac;
     QSqlQuery query(upsdax,current());
     if (query.lastError().isValid())  {
     qDebug() << query.lastError().text(); 
      return false;
      } else {
      return true;
      }
}

int DB_Manager::IdPaese( const int titurism )
{
    QSqlQueryModel *mod = new QSqlQueryModel();
    mod->setQuery(QString("SELECT id FROM %1 WHERE import_id=%2 LIMIT 1").arg(TABELLA_PAESI).arg(titurism),current());
    
    QSqlRecord r = mod->record(0);
    
            if (r.value("id").toInt() > 0) {
            return r.value("id").toInt();
            } else {
            return -1;
            }

}

int DB_Manager::IdTipo( const int tipoditurismo )
{
    QSqlQueryModel *mod = new QSqlQueryModel();
    mod->setQuery(QString("SELECT ID FROM %1 WHERE TIPO_TI=%2 LIMIT 1").arg(TABELLA_TIPO).arg(tipoditurismo),current());
    QSqlRecord r = mod->record(0);
            if (r.value("id").toInt() > 0) {
            return r.value("id").toInt();
            } else {
            return 104;
            }

}

QString DB_Manager::TipoNome( const int idnostro )
{
    QSqlQueryModel *mod = new QSqlQueryModel();
    mod->setQuery(QString("SELECT NAME_IT FROM %1 WHERE ID=%2 LIMIT 1").arg(TABELLA_TIPO).arg(idnostro),current());
    QSqlRecord r = mod->record(0);
            if (r.value("NAME_IT").toString().size() > 0) {
            return r.value("NAME_IT").toString();
            } else {
            return QString("Error");
            }

}






bool DB_Manager::HavingIDOggetto( const int id )
{
    
    QSqlQueryModel *mod = new QSqlQueryModel();
                    mod->setQuery(QString("SELECT CID FROM %1 WHERE ID = %2 LIMIT 1 ")
                                             .arg(TABELLA_CASE)
                                             .arg(id),current());
            QSqlRecord r = mod->record(0);
            if (r.value("CID").toInt() > 0) {
                return true;
            } else {
                return false;
            }
}

int DB_Manager::NuovoOggetto()
{
    QDateTime timer1( QDateTime::currentDateTime() ); 
    const uint datex = timer1.toTime_t();
    QStringList campi =DefaultFieldFrom(TABELLA_CASE,current());
    QStringList pari;
     for (int i = 0; i < campi.size(); ++i)  {
         
         if (i == 1) {
             pari.append(QString("%1").arg(datex));
         } else {
             pari.append(campi.at(i));  
         }
     }
     QString inserter = QString("INSERT INTO %1 VALUES (%2);").arg(TABELLA_CASE).arg(pari.join(","));
     QSqlQuery query(inserter,current());
     
     if (query.lastInsertId().toInt() > 0) {
        return query.lastInsertId().toInt();
     } else {
          
    QSqlQueryModel *mod = new QSqlQueryModel();
                    mod->setQuery(QString("SELECT ID FROM %1 WHERE CID = %2 LIMIT 1 ")
                                             .arg(TABELLA_CASE)
                                             .arg(datex),current());
            QSqlRecord r = mod->record(0);
            return r.value("ID").toInt();
     }
    
    
    
}


bool  DB_Manager::NuovoOggettoID( const int id , uint timer )
{
    
    QStringList campi =DefaultFieldFrom(TABELLA_CASE,current());
    QStringList pari;
    
     for (int i = 0; i < campi.size(); ++i)  {
         
         if (i == 0) {
             pari.append(QString("%1").arg(id));
         } else if (i == 1) {
             pari.append(QString("%1").arg(timer));
         } else {
             pari.append(campi.at(i));  
         }
         
     }
     QString inserter = QString("INSERT INTO %1 VALUES (%2);").arg(TABELLA_CASE).arg(pari.join(","));
     //////////qDebug() << "### inserter " << inserter;
     QSqlQuery query(inserter,current());
     if (query.lastError().isValid())  {
     qDebug() << query.lastError().text(); 
      }
     
     
     return HavingIDOggetto(id);
}

















void DB_Manager::FillBoxRegioni(QComboBox * box , int id )
{
  box->clear();
  box->addItem(tr("Seleziona..."),0); 
  QSqlQueryModel *mod = new QSqlQueryModel();
  mod->setQuery(QString("SELECT id,name,cpa,msm FROM %1 WHERE cpa!=0 order by name").arg(TABELLA_PAESI),current());
    int select = -1;
      const int summline = mod->rowCount();
      for (int e = 0; e < summline; ++e) {
      QSqlRecord r = mod->record(e);
          if (r.value("id").toInt() == id) {
          select = e + 1;
          }
      box->addItem(r.value("id").toString() +") "+ r.value("cpa").toString()+" "+r.value("name").toString()+" m/sm"+r.value("msm").toString(),r.value("id").toInt());  
      }
      
      
  box->setCurrentIndex ( select );
}


void  DB_Manager::FillBoxTipo( QComboBox * boxtipo, int id , int modus )
{
    boxtipo->clear();
    if (modus == 1) {
    boxtipo->addItem(tr("Tutti..."),0); 
    } else if (modus == 0) {
    boxtipo->addItem(tr("Seleziona..."),0); 
    } else {
    boxtipo->addItem(tr("Modus sconosciuto..."),0); 
    }
    QSqlQueryModel *mod = new QSqlQueryModel();
    mod->setQuery(QString("SELECT ID,NAME FROM TIPO_OGGETTI order by ID"),current());
    
     int select = -1;
    
    
      const int summline = mod->rowCount();
      for (int e = 0; e < summline; ++e) {
      QSqlRecord r = mod->record(e);
          const int Xid = r.value("ID").toInt();
          if (Xid == id) {
          select = e + 1;
          }
          boxtipo->addItem(r.value("ID").toString() +") "+ r.value("NAME").toString(),Xid);  
      }
    boxtipo->setCurrentIndex(select);
}

bool  DB_Manager::CestinaId( const int id )
{
    if (id < 1) {
    return false;
    }
    const QString xs = QString("UPDATE APPCASE SET TIPO_1=104 WHERE ID=%1 LIMIT 1").arg(id);
    QSqlQuery query(xs,current());
     if (query.lastError().isValid())  {
     qDebug() << query.lastError().text(); 
     return false;
      } else {
        return true;
      }
    
}


void  DB_Manager::GrepOrfani()
{
    QSqlQueryModel *mod = new QSqlQueryModel();
    
    const QString xs 	= "SELECT ID FROM APPCASE WHERE "
                     "( APPCASE.CID_4 NOT IN ( SELECT DISTINCT id FROM `LUOGHI` WHERE cpa >0 )) "
                     " ORDER BY ID DESC";
    
    
    mod->setQuery(xs,current());
    const int summline = mod->rowCount();
    if (summline > 0) {
        for (int e = 0; e < summline; ++e) {
            QSqlRecord r = mod->record(e);
            CestinaId(r.value("id").toInt()); 
          }
        
    }
    
    
}
    
QMap<QString,QStringList>  DB_Manager::retranslate_now()
{
  QMap<QString,QStringList> qtrans;
	QSqlQueryModel *modt = new QSqlQueryModel();
  modt->setQuery(QString("SELECT NAME AS ID,NAME_IT,NAME_DE,NAME_FR,NAME_EN FROM TRANSLATE"),current());
	const int summline = modt->rowCount();
	if (summline > 0) {
	 qtrans.clear();
			for (int e = 0; e < summline; ++e) {
        QSqlRecord r = modt->record(e);  /* records */
        QStringList linename;
                    linename.clear();
                    linename.append(r.value(1).toString());
                    linename.append(r.value(2).toString());
                    linename.append(r.value(3).toString());
                    linename.append(r.value(4).toString());
			 qtrans.insert(r.value(0).toString(),linename);
			}
  }
  
  //////qDebug() << "### DB_Manager trans count  " << qtrans.size();
  
  return qtrans;
}








void  DB_Manager::FillBoxLuoghi( QComboBox * boxtipo, int id , int modus )
{
    boxtipo->clear();
    if (modus == 1) {
    boxtipo->addItem(tr("Tutti..."),0); 
    boxtipo->addItem(tr("Orfani di paese.."),40004); 
    } else if (modus == 0) {
    boxtipo->addItem(tr("Seleziona..."),0); 
    } else {
    boxtipo->addItem(tr("Modus sconosciuto..."),0); 
    }
    QSqlQueryModel *mod = new QSqlQueryModel();
    mod->setQuery(QString("SELECT id,name,import_id,cpa FROM LUOGHI where cpa !=0 order by name"),current());
    
     int select = 0;
      const int summline = mod->rowCount();
      for (int e = 0; e < summline; ++e) {
      QSqlRecord r = mod->record(e);
          if (r.value("id").toInt() == id) {
              if (modus != 1) {
              select = e + 1;
              } else {
              select = e + 2;
              }
              
          }
          boxtipo->addItem(r.value("name").toString() + "  (" + r.value("import_id").toString() + "/" + r.value("cpa").toString() + "/" + r.value("id").toString() + ")",r.value("id").toInt());  
      }
    boxtipo->setCurrentIndex(select);
}










DB_Manager::~DB_Manager()
{
    Purge();
}
